<?php
App::uses('Xml', 'Utility');
class ArticleController extends ArticleAppController {

	public $cacheAction = array(
			'view' => array('callbacks' => true, 'duration' => 21600)
	);
	
	public function beforeRender(){
		parent::beforeRender();
		$this->layout = 'default';
	}
	public function beforeFilter() {
		$this->Auth->allow('view');
		$this->Auth->allow('review');
		// load configuration form DB
		$this->Configuration->load($this->Session->read('Config.domain_id'));
	}
	
	public function view($article_id = null) {
	
		$slug = func_get_args();
		$options['conditions'] = array('Article.slug'=>$slug,'Article.domain_id'=>$this->Session->read('Config.domain_id'));
		$article = $this->Article->find('first',$options);
		$article_count = $this->Article->find('count',array('conditions'=>array('Article.menuses_id'=>$article['Article']['menuses_id'])));
		if($path = "/"){
			if(isset($article['Article']['submenu_id']) && !is_null($article['Article']['submenu_id'])){
				$this->loadModel('Submenu');
				$this->Submenu->recursive = -1;
				$this->Submenu->id = $article['Article']['submenu_id'];
				$path = Router::url( "/".$this->Submenu->field('slug'), true );
			}else if(isset($article['Article']['menuses_id']) && !is_null($article['Article']['menuses_id'])){
				$this->loadModel('Menus');
				$this->Menus->recursive = -1;
				$this->Menus->id = $article['Article']['menuses_id'];
				$path = Router::url( "/".$this->Menus->field('slug'), true );
				
			}
		}
		
		$path = explode("/", $path);
		$path = $path[count($path)-1];
		$path = array(0=>$path);
		// slugs from menuses
		$links = $this->Menu->getMenu($path);
		$count = count($path);
		if (!$count) {
			$this->redirect('/');
		}
		
	
		if(array_key_exists($path[0], $links) && !empty($path[0])){

			$title_for_layout = $article['Article']['name'];
			$article_meta_tags = $article['Article']['metas'];
			$keywords = $article['Article']['keywords'];
			$description = $article['Article']['descriptions'];
			$patchArticle = array('name'=>$article['Article']['name'],'slug'=>$article['Article']['slug']);
			
			$options['joins'] = array(
			array('table' => 'articles_uploads',
										        'alias' => 'ArticlesUpload',
										        'type' => 'inner',
										        'conditions' => array(
										            'Upload.id = ArticlesUpload.upload_id'
			)
			),
			array('table' => 'articles',
										        'alias' => 'Article',
										        'type' => 'inner',
										        'conditions' => array(
										            'ArticlesUpload.article_id = Article.id'
			)
			)
			);
			
			$options['order'] = array(
												    'Upload.type'
			);
			
			$options_rating['joins'] = array(
			array('table' => 'rating_articles',
												        'alias' => 'RatingArticle',
												        'type' => 'inner',
												        'conditions' => array(
												            'Rating.id = RatingArticle.rating_id'
			)
			),
			array('table' => 'articles',
												        'alias' => 'Article',
												        'type' => 'inner',
												        'conditions' => array(
												            'RatingArticle.article_id = Article.id'
			)
			)
			);
			
			$options_rating['order'] = array(
														    'Rating.name'
			);
			
			$options_rating_values['joins'] = array(
			array('table' => 'articles',
												        'alias' => 'Article',
												        'type' => 'inner',
												        'conditions' => array(
												            'RatingValue.article_id = Article.id'
			)
			)
			);
			
			
			$options_comments['joins'] = array(
			array('table' => 'articles_comments',
														        'alias' => 'ArticlesComment',
														        'type' => 'inner',
														        'conditions' => array(
														            'Comment.id = ArticlesComment.comment_id'
			)
			),
			array('table' => 'articles',
														        'alias' => 'Article',
														        'type' => 'inner',
														        'conditions' => array(
														            'ArticlesComment.article_id = Article.id'
			)
			)
			);
			
			$options_posts['joins'] = array(
			array('table' => 'posts_articles',
														        'alias' => 'PostsArticle',
														        'type' => 'inner',
														        'conditions' => array(
														            'Post.id = PostsArticle.post_id'
			)
			),
			array('table' => 'articles',
														        'alias' => 'Article',
														        'type' => 'inner',
														        'conditions' => array(
														            'PostsArticle.article_id = Article.id'
			)
			)
			);
			
			$this->loadModel('Upload');
			$this->Upload->recursive = -1;
			$this->loadModel('Rating');
			$this->Rating->recursive = -1;
			$this->loadModel('RatingValue');
			$this->RatingValue->recursive = -1;
			$this->loadModel('Comment');
			$this->Comment->recursive = -1;
			$this->loadModel('Post');
			$this->Post->recursive = -1;
			
			$options['conditions'] = array( 'Article.id' => $article['Article']['id'] );
			$files_ = $this->Upload->find('all',$options);
			
			$options_rating['conditions'] = array( 'Article.id' => $article['Article']['id'], 'Rating.status' => 1 );
			$ratings = $this->Rating->find('all',$options_rating);
			
			$options_rating_values['conditions'] = array( 'Article.id' => $article['Article']['id']);
			$rating_values = $this->RatingValue->find('all',$options_rating_values);
			$total_ratings = count($rating_values);
			$rating_values = $this->Articles->prepare_rating_values($rating_values,$total_ratings);
			
			$total_calculate = array();
			$total_calculate['count'] = 0;
			$total_calculate['sum'] = 0;
			$i = 1;
			foreach ($rating_values as $rating_id => $rrow) {
				$total_calculate['count'] = $total_calculate['count'] + $rrow['count'];
				$total_calculate['sum'] = $total_calculate['sum'] + $rrow['sum'];
				if($total_calculate['count'] != 0) $total_calculate['serd'] = round( $total_calculate['sum'] / $total_calculate['count']  ,0);
				if($total_calculate['count'] != 0) $total_calculate['proc'] = $i  * 100 /$total_calculate['count'];
			
				$i++;
			}
			$rating_values['total'] = $total_calculate;
			
			
			$options_comments['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Comment.status' => 1 );
			$comments = $this->Comment->find('all',$options_comments);
				
			$options_posts['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Post.status' => 1 );
			$posts = $this->Post->find('all',$options_posts);
			
			$gallery = array();
			$download = array();
			if(is_array($files_)){
				foreach ($files_ as $key2 => $file) {
// 					$this->Uploads->upload_file(Configure::read('Config.panel_uploads_folder').$file['Upload']['name'], Configure::read('Config.loacl_uploads_folder'), $file['Upload']['name'], false);
					if(
						$file['Upload']['type'] == 'image/jpeg' ||  
						$file['Upload']['type'] == 'image/jpg' || 
						$file['Upload']['type'] == 'image/png' || 
						$file['Upload']['type'] == 'image/gif')
					{
						array_push($gallery, $file);				
					}
					if(	$file['Upload']['type'] == 'application/pdf' ||
						$file['Upload']['type'] == 'application/zip'
					)
					{
						array_push($download, $file);
					}
				}
			}
			
			$article['Gallery'] = $gallery;
			$article['Download'] = $download;
			$article['Rating'] = $ratings;
			$article['RatingValue'] = $rating_values;
			$article['RatingTotal'] = $total_ratings;
			$article['Comment'] = $comments;
			$article['Post'] = $posts;
			
			$this->set(compact('article', 'title_for_layout','keywords','description','article_meta_tags','patchArticle','article_count'));
			
			
			$this->render(implode('/', array('view')));		
			

		}
		
	}
	

	
	public function review() {
		// 					$this->helpers[] = 'Recaptcha.Recaptcha';
		// 					$this->Components->load('Recaptcha.Recaptcha')->startup($this);
		// 					Configure::load('Recaptcha.key');
		
		$slug = func_get_args();
		$options['conditions'] = array('Article.slug'=>$slug,'Article.domain_id'=>$this->Session->read('Config.domain_id'));
		$article = $this->Article->find('first',$options);
			
		if($path = "/"){
			if(isset($article['Article']['submenu_id']) && !is_null($article['Article']['submenu_id'])){
				$this->loadModel('Submenu');
				$this->Submenu->recursive = -1;
				$this->Submenu->id = $article['Article']['submenu_id'];
				$path = Router::url( "/".$this->Submenu->field('slug'), true );
			}else if(isset($article['Article']['menuses_id']) && !is_null($article['Article']['menuses_id'])){
				$this->loadModel('Menus');
				$this->Menus->recursive = -1;
				$this->Menus->id = $article['Article']['menuses_id'];
				$path = Router::url( "/".$this->Menus->field('slug'), true );
			}
		}
	
		if ($this->request->is('post')) {
				
// 			debug($this->request->data); die;
	
			$this->request->data['Comment']['domain_id'] = $this->Session->read('Config.domain_id');
			$this->request->data['Comment']['ipv4'] = $this->request->clientIp();
				
			if(isset($this->request->data['RatingValue'])){
				$this->loadModel('RatingValue');
				foreach ($this->request->data['RatingValue'] as $rating_id => $value) {
					unset($this->request->data['RatingValue'][$rating_id]);
					array_push($this->request->data['RatingValue'],
					array(
					'article_id'=> (string)$this->request->data['Article']['Article'][0],
					'rating_id'=> (string)$rating_id,
					'rating_value'=> (string)$value ));
				}
// 				debug($this->request->data); die;
				$this->RatingValue->create();
				if ($this->RatingValue->saveAll($this->request->data['RatingValue'], array('deep' => true))) {
					$this->Session->setFlash(__d('articles','The ratings has been saved'));
	
				} else {
					$this->Session->setFlash(__d('articles','The ratings could not be saved. Please, try again.'));
				}
			}
			
			$this->loadModel('Comment');
			$this->Comment->set($this->request->data);
			if ($this->Comment->validates()) {
				$this->Comment->create();
				if ($this->Comment->save($this->request->data)) {
					$this->Session->setFlash(__d('articles','The comment has been saved'));
	
				} else {
					$this->Session->setFlash(__d('articles','The comment could not be saved. Please, try again.'));
				}
	
				$this->redirect($path);
			}
	
	
				
		}

	
		/*
		$path = explode("/", $path);
		$path = $path[count($path)-1];
		$path = array(0=>$path);
		// slugs from menuses
		$links = $this->Menu->getMenu($path);
		$count = count($path);
		if (!$count) {
			$this->redirect('/');
		}
	
	
		if(array_key_exists($path[0], $links) && !empty($path[0])){
	
			$title_for_layout = $article['Article']['name'];
			$article_meta_tags = $article['Article']['metas'];;
			$keywords = $article['Article']['keywords'];
			$description = $article['Article']['descriptions'];
			$patchArticle = array('name'=>$article['Article']['name'],'slug'=>$article['Article']['slug']);
				
			$options['joins'] = array(
					array('table' => 'articles_uploads',
							'alias' => 'ArticlesUpload',
							'type' => 'inner',
							'conditions' => array(
									'Upload.id = ArticlesUpload.upload_id'
							)
					),
					array('table' => 'articles',
							'alias' => 'Article',
							'type' => 'inner',
							'conditions' => array(
									'ArticlesUpload.article_id = Article.id'
							)
					)
			);
				
			$options['order'] = array(
					'Upload.type'
			);
				
			$options_rating['joins'] = array(
					array('table' => 'rating_articles',
							'alias' => 'RatingArticle',
							'type' => 'inner',
							'conditions' => array(
									'Rating.id = RatingArticle.rating_id'
							)
					),
					array('table' => 'articles',
							'alias' => 'Article',
							'type' => 'inner',
							'conditions' => array(
									'RatingArticle.article_id = Article.id'
							)
					)
			);
				
			$options_rating['order'] = array(
					'Rating.name'
			);
				
			$options_rating_values['joins'] = array(
					array('table' => 'articles',
							'alias' => 'Article',
							'type' => 'inner',
							'conditions' => array(
									'RatingValue.article_id = Article.id'
							)
					)
			);
				
				
			$options_comments['joins'] = array(
					array('table' => 'articles_comments',
							'alias' => 'ArticlesComment',
							'type' => 'inner',
							'conditions' => array(
									'Comment.id = ArticlesComment.comment_id'
							)
					),
					array('table' => 'articles',
							'alias' => 'Article',
							'type' => 'inner',
							'conditions' => array(
									'ArticlesComment.article_id = Article.id'
							)
					)
			);
				
			$options_posts['joins'] = array(
					array('table' => 'posts_articles',
							'alias' => 'PostsArticle',
							'type' => 'inner',
							'conditions' => array(
									'Post.id = PostsArticle.post_id'
							)
					),
					array('table' => 'articles',
							'alias' => 'Article',
							'type' => 'inner',
							'conditions' => array(
									'PostsArticle.article_id = Article.id'
							)
					)
			);
				
			$this->loadModel('Upload');
			$this->Upload->recursive = -1;
			$this->loadModel('Rating');
			$this->Rating->recursive = -1;
			$this->loadModel('RatingValue');
			$this->RatingValue->recursive = -1;
			$this->loadModel('Comment');
			$this->Comment->recursive = -1;
			$this->loadModel('Post');
			$this->Post->recursive = -1;
				
			$options['conditions'] = array( 'Article.id' => $article['Article']['id'] );
			$files_ = $this->Upload->find('all',$options);
				
			$options_rating['conditions'] = array( 'Article.id' => $article['Article']['id'], 'Rating.status' => 1 );
			$ratings = $this->Rating->find('all',$options_rating);
				
			$options_rating_values['conditions'] = array( 'Article.id' => $article['Article']['id']);
			$rating_values = $this->RatingValue->find('all',$options_rating_values);
			$total_ratings = count($rating_values);
			$rating_values = $this->Articles->prepare_rating_values($rating_values,$total_ratings);
				
			$options_comments['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Comment.status' => 1 );
			$comments = $this->Comment->find('all',$options_comments);
	
			$options_posts['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Post.status' => 1 );
			$posts = $this->Post->find('all',$options_posts);
				
			$gallery = array();
			$download = array();
			if(is_array($files_)){
				foreach ($files_ as $key2 => $file) {
					$this->Uploads->upload_file(Configure::read('Config.panel_uploads_folder').$file['Upload']['name'], Configure::read('Config.loacl_uploads_folder'), $file['Upload']['name'], false);
					if(
							$file['Upload']['type'] == 'image/jpeg' ||
							$file['Upload']['type'] == 'image/jpg' ||
							$file['Upload']['type'] == 'image/png' ||
							$file['Upload']['type'] == 'image/gif')
					{
						array_push($gallery, $file);
					}
					if(	$file['Upload']['type'] == 'application/pdf' )
					{
						array_push($download, $file);
					}
				}
			}
				
			$article['Gallery'] = $gallery;
			$article['Download'] = $download;
			$article['Rating'] = $ratings;
			$article['RatingValue'] = $rating_values;
			$article['RatingTotal'] = $total_ratings;
			$article['Comment'] = $comments;
			$article['Post'] = $posts;
				
			$this->set(compact('article', 'title_for_layout','keywords','description','article_meta_tags','patchArticle'));
				
				
			$this->render(implode('/', array('review')));
				
	
		}
		
		*/
	
	}
	
}